from flask import Blueprint, render_template, redirect, url_for, session, request, json
from form import RegisterForm, LoginForm, CancenlationForm
from werkzeug.security import generate_password_hash, check_password_hash
from models import UserModel, ObjectModel
from exts import db
from werkzeug.datastructures import ImmutableMultiDict

bp = Blueprint("user",__name__,url_prefix="/user")

@bp.route("/login", methods=['Post'])
def login():
    if request.method == 'GET':
        return {
            "state":False,
            "message": "请登录"  # 返回登录页面
        }
    else:
        json = request.json
        form = LoginForm(ImmutableMultiDict(json))
        # if form.validate():
        username = form.username.data
        password = form.password.data
        user = UserModel.query.filter_by(username=username).first()
        if not user:
            return {
                "state": False,
                "message": "用户不存在"  # 返回登录页面
            }
        else:
            if check_password_hash(user.password, password):
                # cookie:不适合存储太多数据，一般用来存放登录授权的东西
                # flask中的session: 经过加密后存储在cookie中
                session['user_id'] = user.id
                user_id = UserModel.query.filter_by(username=username).first().id
                return {
                    "state": True,
                    "message": "登录成功",  # 返回登录页面
                    "user_id": user_id,
                    "username": username
                }
            else:
                return {
                    "state": False,
                    "message": "密码错误"  # 返回登录页面
                }
        # else:
        #     return {
        #         "state": False,
        #         "message": form.errors  # 返回登录页面
        #     }

@bp.route("/register", methods=['POST'])
def register():
    # db, cursor = get_db()
    json = request.json
    form = RegisterForm(ImmutableMultiDict(json))
    # a = json.loads(request.get_data())
    if form.validate():
        username = json.get('username')
        user1 = UserModel.query.filter_by(username=username).first()
        if not user1:
            password = json.get('password')
            # email = json.get('email')
            # wechat = json.get('wechat')
            user = UserModel(username=username, password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            return {
                "state": True,
                "message":"register success"
            }
        else:
            return {
                "state": False,
                "message": "该用户名已存在"
            }
    else :
        return {
            "state": False,
            "message": form.errors
        }
    # # #表单验证：flask-wtf
    # form = RegisterForm(request.form)
    # if form.validate():
    #     email = form.email.data
    #     username = form.username.data
    #     password = form.password.data
    #     wechat = form.wechat.data
    #     user = Usermodel(email=email,username=username,password=generate_password_hash(password),wechat=wechat)
    #     db.session.add(user)
    #     db.session.commit()
    #     return redirect(url_for("user.login"))  # 跳转到登录页面
    # else:
    #     return "注册失败" # 返回注册页面

@bp.route("/cancellation", methods = ["GET", "POST"])
def cancellation():
    json = request.json
    form = CancenlationForm(ImmutableMultiDict(json))
    # a = json.loads(request.get_data())
    if form.validate():
        username = json.get('username')
        # password = json.get('password')
        user = UserModel.query.filter_by(username=username).first()
        if not user:
            return {
                "state": False,
                "message": "用户不存在"
            }
        db.session.delete(user)
        db.session.commit()
        return {
            "state": True,
            "message": "cancellation success"
        }
    else:
        return {
            "state": False,
            "message": form.errors
        }